package com.buddy.learn.algorithm.exam;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author Buddy
 * @date 2021/5/19
 */
public class Solution {

    static final String OPTStr = "+-*/";

    public static void main(String[] args) {

        /**
         * 字符串 计算
         */
        String orig = "10+3*5/15-2";
        // 先对字符串做处理
        char[] chars = orig.toCharArray();
        List<String> list = new ArrayList<>();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if (OPTStr.indexOf(c) > -1) {
                list.add(sb.toString());
                sb = new StringBuffer();
                list.add(c + "");
            } else {
                sb.append(c);
            }
        }
        if (sb.length() > 0) {
            list.add(sb.toString());
        }

        System.out.println(calStr(list));

    }

    private static String calStr(List<String> list) {
        String res = "0";
        Stack<String> stack = new Stack<>();
        Stack<String> stack2 = new Stack<>();
        for (int i = 0; i < list.size(); ) {
            String str = list.get(i);
            if (OPTStr.indexOf(str) > 1) {
                String pre = stack.pop();
                String next = list.get(i + 1);
                String r;
                if (OPTStr.indexOf(str) == 2) {
                    // c 和 pre做乘法运算
                    r = Integer.parseInt(pre) * Integer.parseInt(next) + "";
                } else {
                    // c 和 pre做除法运算
                    r = Integer.parseInt(pre) / Integer.parseInt(next) + "";
                }
                i = i + 2;
                stack.push(r);
            } else {
                i = i + 1;
                stack.push(str);
            }
        }

        while (!stack.isEmpty()) {
            stack2.push(stack.pop());
        }
        while (!stack2.isEmpty()) {
            String str = stack2.pop();
            if (OPTStr.contains(str)) {
                String next = stack2.pop();
                if (OPTStr.indexOf(str) == 0) {
                    // 加
                    res = Integer.parseInt(res) + Integer.parseInt(next) + "";
                } else {
                    // 减
                    res = Integer.parseInt(res) - Integer.parseInt(next) + "";
                }
            } else {
                res = str;
            }
        }

        return res;
    }

}
